package main

import (
	"apiTool/tool"
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
)

//主页
func index(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("./view/index.html") //解析模板文件
	t.Execute(w, nil)
}

//json格式化
func jsonformat(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("./view/jsonformat.html") //解析模板文件
	t.Execute(w, nil)
}

//发送Http请求
func sendHttp(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()                                             //初始化form，只有这样才能获取到值
	requestType := map[string]string{"1": "GET", "2": "POST"} //定义map

	var objs tool.S
	data := []byte(r.Form["param"][0])
	err := json.Unmarshal(data, &objs) //解析json数据格式
	if err != nil {
		fmt.Println("err", err)
	}

	url := r.Form["url"][0]
	types := r.Form["type"][0]
	types = requestType[types]
	//发送请求，返回结果
	body, header, err := tool.HttpRequest(url, types, &objs)
	if err != nil {
		//w.Write([]byte(err))
		fmt.Println("err", err)
	}
	responseBody := map[string]string{"success": "true", "body": body, "header": header}
	responseBody1, err := json.Marshal(responseBody)
	w.Write([]byte(string(responseBody1)))
}

//入口函数
func main() {
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) //启动静态资源，否则就会读取不出来
	http.HandleFunc("/", index)                                                                //设置访问路由
	http.HandleFunc("/jsonformat", jsonformat)
	http.HandleFunc("/sendHttp", sendHttp)   //设置访问路由
	err := http.ListenAndServe(":9091", nil) //监听端口
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
